package 翻译程序;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//翻译程序的客户端和回显程序的客户端基本类似
public class UdpDictClient {
    private DatagramSocket  socket=null;
    private String serverIp;
    private int serverPort;

    public UdpDictClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp=serverIp;
        this.serverPort=serverPort;
        this.socket=new DatagramSocket();//IP为本机IP，端口号由操作系统分配
    }

    public void start() throws IOException {
        System.out.println("请输入查询的单词");
        Scanner scanner=new Scanner(System.in);
        while (true) {
            //1.读取用户的输入
            String request=scanner.next();
            if (request.equals("exit")) {
                System.out.println("程序退出！");
                return;
            }

            //2.根据输入构造请求,并将请求发送给 服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);//后两个参数为 服务器的IP和端口号

            socket.send(requestPacket);

            //3.从服务器中读取响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            //4.将响应显示给用户
            String log=String.format("request: %s , response:%s",request,response);
            System.out.println(log);

        }
    }

    public static void main(String[] args) throws IOException {
        UdpDictClient client=new UdpDictClient("127.0.0.1",9090);
        client.start();
    }
}
